<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout}">

<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- 日期选择器 -->
    <title>实名认证</title>
    <style>
        .auth-card {
            max-width: 700px;
            margin: 2rem auto;
        }
        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
        }
        .form-note {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }
        .address-group .form-control {
            margin-bottom: 0.5rem;
        }
    </style>
</head>
<body class="bg-light">
<div layout:fragment="content">
    <div class="auth-card card">
        <div class="card-header">
            <h2 class="h5 mb-0">用户实名认证</h2>
        </div>
        <div class="card-body">
            <form th:action="@{/api/real_name_auth/save}" method="post" th:object="${authData}" enctype="multipart/form-data">
                <!-- 提示信息 -->
                <div class="alert alert-danger alert-dismissible fade show"
                     th:classappend="${successMessage} ? 'alert-success' : ''"
                     role="alert"
                     th:if="${errorMessage} or ${successMessage}">
                    <span th:text="${successMessage} ?: ${errorMessage}"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>

                <!-- 基础信息 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">真实姓名</label>
                        <input type="text" class="form-control" th:field="*{name}" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">性别</label>
                        <div class="btn-group w-100">
                            <input type="radio" class="btn-check" name="gender" id="male" value="M" th:checked="(*{gender} == 'M')">
                            <label class="btn btn-outline-primary" for="male">男</label>

                            <input type="radio" class="btn-check" name="gender" id="female" value="F" th:checked="(*{gender} == 'F')">
                            <label class="btn btn-outline-primary" for="female">女</label>
                        </div>
                    </div>
                </div>

                <!-- 证件信息 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">身份证号码</label>
                        <input type="text" class="form-control"
                               th:field="*{idCard}"
                               name="idCard"
                               pattern="\d{17}[\dXx]"
                               required>
                        <div class="form-note">请填写第二代居民身份证号码</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">出生日期</label>
                        <input type="date" class="form-control"
                               th:field="*{birthday}"
                               name="birthday"
                               id="birthdayPicker">
                    </div>
                </div>

                <!-- 联系信息 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">手机号码</label>
                        <input type="tel" class="form-control"
                               th:field="*{phone}"
                               name="phone"
                               pattern="1[3-9]\d{9}">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">邮政编码</label>
                        <input type="number" class="form-control"
                               th:field="*{administrativeRegion.code}"
                               name="code"
                               id="codeId"
                               readonly>
                    </div>
                </div>

                <!-- 地址选择 -->
                <div class="mb-3 address-group">
                    <label class="form-label">地址选择</label>
                    <div class="row">
                        <div class="col-3">
                            <select class="form-select" id="provinceSelect" onchange="changeNext(this,$('#citySelect'))">
                                <option value="">选择省份</option>
                            </select>
                        </div>
                        <div class="col-3">
                            <select class="form-select" id="citySelect" onchange="changeNext(this,$('#townSelect'))" disabled>
                                <option value="">选择城市</option>
                            </select>
                        </div>
                        <div class="col-3">
                            <select class="form-select" id="townSelect" onchange="changeNext(this,$('#streetSelect'))" disabled>
                                <option value="">选择区县</option>
                            </select>
                        </div>
                        <div class="col-3">
                            <select class="form-select" id="streetSelect" onchange="changeNext(this,null)" disabled>
                                <option value="">选择街道</option>
                            </select>
                        </div>
                    </div>

                    <div class="mt-2">
                        <input type="text" class="form-control"
                               placeholder="详细地址（门牌号等）"
                               name="addressDetail"
                               th:field="*{addressDetail}">
                    </div>
                    <div class="mt-2" th:if="(*{administrativeRegion.code} != null)">
                        <label class="form-label">已选地址</label>
                        <input type="text" class="form-control"
                               th:field="*{administrativeRegion.nameChain}"
                               disabled>
                    </div>
                </div>

                <!-- 头像上传 -->
                <div class="mb-4">
                    <label class="form-label">头像上传</label>
                    <div class="flex-grow-1">
                        <input type="file" class="form-control"
                               name="avatar" id="avatarInput"
                               accept="image/jpeg, image/png"
                               onchange="validateAndPreview(this)">
                        <div class="form-note">支持 JPG/PNG 格式，大小不超过 2MB</div>
                        <div id="errorMsg" class="text-danger mt-1"></div>
                        <img th:src="@{'data:image/jpeg;base64,' + ${authData.avatarBase64}}" id="preview" class="mt-2" style="max-width: 200px;">
                    </div>
                </div>

                <!-- 隐藏字段 -->
                <input type="hidden" name="createTime" th:field="*{createTime}">
                <input type="hidden" name="updateTime" th:field="*{updateTime}">

                <!-- 提交按钮 -->
                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                    <a href="/api/real_name_auth/export-excel" class="btn btn-outline-secondary"
                    th:if="${session.user.hasRole(4) || session.user.hasRole(8)}">导出所有用户数据为Excel</a>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check2-circle me-2"></i>提交认证
                    </button>
                    <a href="/api/drugs" class="btn btn-outline-secondary">返回首页</a>
                </div>
            </form>
        </div>
    </div>
    <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script layout:fragment="script">
        // 头像预览功能
        // function previewAvatar(input) {
        //     if (input.files && input.files[0]) {
        //         const reader = new FileReader();
        //         reader.onload = function(e) {
        //             document.getElementById('avatarPreview').src = e.target.result;
        //         }
        //         reader.readAsDataURL(input.files[0]);
        //     }
        // }

        function loadProvince(input) {
            if(input != null){
                $.ajax({
                    url: "/api/region/findRegion", // 建议使用绝对路径
                    type: "POST",
                    contentType: "application/json", // 关键设置
                    data: JSON.stringify({ pid: -1 }), // 序列化为 JSON
                    success: function(data) {
                        const $province = $('#provinceSelect');
                        $province.empty().append('<option value="">请选择</option>');
                        data.forEach(region => {
                            $province.append(
                                $('<option></option>')
                                    .val(region.code)
                                    .text(region.name)
                            );
                        });
                    },
                    error: function() {
                        $('#provinceSelect').html('<option value="">数据加载失败</option>');
                        console.error('区域数据加载异常');
                    }
                });
            }
        }

        function changeNext(input, next){
            if(input != null){
                $('#codeId').val(input.value)
                if(next != null){
                    if (!input.value) return
                    $.ajax({
                        url: "/api/region/findRegion", // 建议使用绝对路径
                        type: "POST",
                        contentType: "application/json", // 关键设置
                        data: JSON.stringify({ pid: input.value }), // 序列化为 JSON
                        success: function (data){
                            next.empty().append('<option value="">请选择</option>')
                            next.prop('disabled', false)
                            data.forEach(region => {
                                next.append(
                                    $('<option></option>')
                                        .val(region.code)
                                        .text(region.name)
                                )
                            })
                        },
                        error: function() {
                            $('#provinceSelect').html('<option value="">数据加载失败</option>');
                            console.error('区域数据加载异常');
                        }
                    });
                }
            }
        }
        $(document).ready(function (){
            loadProvince($('#provinceSelect'))
        });

        function validateAndPreview(input) {
            const errorMsg = document.getElementById('errorMsg');
            const preview = document.getElementById('preview');
            const file = input.files[0];

            // 清除旧数据和错误提示
            errorMsg.textContent = '';
            preview.style.display = 'none';

            // 1. 验证文件存在性
            if (!file) {
                errorMsg.textContent = '请选择文件';
                input.value = ''; // 清空输入
                return;
            }

            // 2. 验证文件类型
            const allowedTypes = ['image/jpeg', 'image/png'];
            if (!allowedTypes.includes(file.type)) {
                errorMsg.textContent = '仅支持 JPG/PNG 格式';
                input.value = '';
                return;
            }

            // 3. 验证文件大小
            const maxSizeMB = 2;
            if (file.size > maxSizeMB * 1024 * 1024) {
                errorMsg.textContent = `文件大小不能超过 ${maxSizeMB}MB`;
                input.value = '';
                return;
            }

            // 4. 预览图片
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);

        }
    </script>
</div>

</body>
</html>